package com.liliudong.rommath.plugin.storage.config;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.common.comm.SignVersion;
import com.liliudong.rommath.plugin.storage.properties.StorageConfigProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 存储自动装配类
 *
 * @author liliudong
 * @date 2025年01月04日 10:29
 */
@Configuration
@EnableConfigurationProperties(StorageConfigProperties.class)
public class StorageAutoConfiguration {

    @Bean
    @ConditionalOnClass(OSS.class)
    public OSS ossClient(StorageConfigProperties storageConfigProperties) {
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        DefaultCredentialProvider credentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider(storageConfigProperties.getAccessKey(), storageConfigProperties.getSecretKey());
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        clientBuilderConfiguration.setProtocol(Protocol.HTTPS);
        return OSSClientBuilder.create()
                .endpoint(storageConfigProperties.getEndpoint())
                .credentialsProvider(credentialProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(storageConfigProperties.getRegion())
                .build();
    }

}
